import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class RecipeSearchHistoryNotifier
    extends AutoDisposeAsyncNotifier<List<String>> {
  @override
  Future<List<String>> build() async {
    return await fetchData();
  }

  Future<void> inserData(String tag) async {
    final spUtils = await SPUtils.getInstance();
    bool ret = await spUtils.headStringList(
      CommonConfig.KrecipeSearchKeyWordHistory,
      [tag],
    );
    if (ret) {
      fetchData();
    }
    return;
  }

  Future<List<String>> fetchData() async {
    final spUtils = await SPUtils.getInstance();
    List<String> strList = spUtils.getStringList(
      CommonConfig.KrecipeSearchKeyWordHistory,
    );
    state = AsyncData(strList);
    return strList;
  }

  Future<void> clear() async {
    final spUtils = await SPUtils.getInstance();
    spUtils.remove(CommonConfig.KrecipeSearchKeyWordHistory);
    state = AsyncData([]);
    return;
  }
}

final recipeSearchHistoryProvider =
    AutoDisposeAsyncNotifierProvider<RecipeSearchHistoryNotifier, List<String>>(
      RecipeSearchHistoryNotifier.new,
    );
